<template>
  <ContentWrap class="chem-record-wrap">
    <!-- 标题和添加一行按钮 -->
    <div class="chem-header">
<!--      <el-button type="primary" @click="addRow">新增</el-button>-->
      第{{formData.samplingPeriod}}天采样
    </div>
    <!-- 头部信息表单 -->
    <el-form :model="form" class="chem-form" label-width="90px">
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="采样日期">
            <el-date-picker
              v-model="form.sampleDate"
              placeholder="请从气象记录中添加"
              disabled
              style="width: 100%"
              type="date"
              value-format="YYYY-MM-DD"
              @change="emitChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="气压">
            <div class="input-with-unit">
              <el-input v-model="form.airPressure" placeholder="请输入气压" @change="emitChange" />
              <span class="unit-text">kPa</span>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="湿度">
            <div class="input-with-unit">
              <el-input v-model="form.humidity" placeholder="请输入湿度" @change="emitChange" />
              <span class="unit-text">%RH</span>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="检测类别">
            <el-input v-model="form.type" placeholder="请输入" @change="emitChange" />
          </el-form-item>
        </el-col>

      </el-row>
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="标准声源">
            <el-input
              v-model="form.calibrateSoundInfo"
              :title="form.calibrateSoundInfo"
              placeholder="标准声源"
              @change="emitChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="测量仪器信息">
            <el-input
              v-model="form.samplingInstrumentInfo"
              placeholder="请从列表中选择采测量仪器"
              @change="emitChange"
              readonly
            />
          </el-form-item>
        </el-col>


      </el-row>
    </el-form>
    <!-- 表格 -->
    <el-table :data="form.table" border class="chem-table" stripe>
      <el-table-column align="center" label="测量编号" prop="sampleNo" width="240">
        <template #default="{ row }">
          <el-input v-model="row.sampleNo" placeholder="" @change="emitChange" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="工作场所" prop="workplace"  width="150">
        <template #default="{ row }">
          <el-input v-model="row.workplace" placeholder="" @change="emitChange" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="检测岗位" prop="detectionPost"  width="150">
        <template #default="{ row }">
          <el-input v-model="row.detectionPost" placeholder="" @change="emitChange" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="测量对象/佩戴人员" prop="sampleObjectLocationed" width="150">
        <template #default="{ row, $index }">
          <el-select
            clearable
            allow-create
            filterable
            :model-value="getSingleSelect(row.sampleObjectLocation)"
            placeholder="请选择"
            @update:model-value="(val) => setSingleSelect(row, val)"
            style="width: 100%"
          >
            <el-option
              v-for="(item, index) in getSampleObjectLocationOptions($index)"
              :key="index"
              :label="item"
              :value="item"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column align="center" label="仪器编号" prop="samplingEquipmentNo" width="150">
        <template #default="{ row, $index }">
          <el-input
            v-model="row.samplingEquipmentNo"
            placeholder="双击选择测量仪器"
            readonly
            @change="emitChange"
            @dblclick="openFacilityDialog($index, 'samplingEquipmentNo')"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" label="标准声源(型号、编号)" prop="standardNoiseSource" width="80">
        <template #default="{ row, $index }">
          <el-input
            v-model="row.standardNoiseSource"
            placeholder="双击选择标准声源"
            readonly
            @change="emitChange"
            @dblclick="openFacilityDialog($index, 'standardNoiseSource')"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" label="测量起止时间" width="190">
        <template #default="{ row }">
          <el-time-picker
            v-model="row.timeRange"
            end-placeholder="结束时间"
            format="HH:mm"
            is-range
            range-separator="至"
            start-placeholder="开始时间"
            style="width: auto"
            value-format="HH:mm"
            @change="emitChange"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" label="测量校准[dB]">
        <el-table-column align="center" label="测量前读数值" prop="calibrationBefore">
          <template #default="{ row }">
            <el-input v-model="row.calibrationBefore" placeholder="" @change="emitChange" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="测量后读数值" prop="calibrationAfter">
          <template #default="{ row }">
            <el-input v-model="row.calibrationAfter" placeholder="" @change="emitChange" />
          </template>
        </el-table-column>
      </el-table-column>

      <el-table-column align="center" label="测量时长" prop="sampleDuration" width="60">
        <template #default="{ row }">
          <el-input v-model="row.sampleDuration" placeholder="" @change="emitChange" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="LAeq,Te[dB(A)]" prop="laeqTe"  width="55">
        <template #default="{ row }">
          <el-input v-model="row.laeqTe" placeholder="" @change="emitChange" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="代表时间">
        <el-table-column align="center" label="h/d" prop="dh">
          <template #default="{ row }">
            <el-input v-model="row.dh" placeholder="" @change="emitChange" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="d/w" prop="dw">
          <template #default="{ row }">
            <el-input v-model="row.workDays" placeholder="" @change="emitChange" />
          </template>
        </el-table-column>
      </el-table-column>


      <el-table-column align="center" label="设备运行情况" prop="productionStatus" width="60">
        <template #default="{ row }">
          <el-input v-model="row.productionStatus" placeholder="" @change="emitChange" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="个体防护情况" prop="earWearStatus" width="60">
        <template #default="{ row }">
          <el-input v-model="row.earWearStatus" placeholder="" @change="emitChange" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="备注" prop="remark">
        <template #default="{ row }">
          <el-input v-model="row.remark" placeholder="" @change="emitChange" />
        </template>
      </el-table-column>
    </el-table>
  </ContentWrap>

  <!-- 设备选择对话框 -->
  <el-dialog
    v-model="facilityDialogVisible"
    append-to-body
    destroy-on-close
    title="选择设备"
    width="60%"
  >
    <div class="dialog-content">
      <Facility
        :instrument-type="instrumentType"
        :default-status="1"
        :show-selection="false"
        @selection-change="handleFacilitySelectionChange"
        @handle-facility-confirm="handleFacilityConfirm"
      />
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="facilityDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleFacilityConfirm">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { computed, onMounted, ref, watch, inject } from 'vue'
import { ElMessage } from 'element-plus'
import ContentWrap from '@/components/ContentWrap/src/ContentWrap.vue'
import { useRoute, useRouter } from 'vue-router'
import Facility from '@/views/infra/facility/facility.vue'

// 新增type和formData prop
const props = defineProps<{
  type: string
  labelName: string
  weatherRecords?: WeatherRecord
  formData?: any
}>()

interface WeatherRecord {
  id: string
  sampleDate: string
  temperature: string
  airPressure: string
  humidity: string
}


const emit = defineEmits(['change'])
const facilityDialogVisible = ref(false)
const label = ref('')
const instrumentType = ref('')
const currentRowIndex = ref<number | null>(null)
const currentColumnProp = ref<string | null>(null)
const selectedFacility = ref<any>(null)
// 保存完整的选项列表，不会因为用户选择而变化
const originalOptionsMap = ref<Map<number, string[]>>(new Map())

const route = useRoute()
const router = useRouter()
defineOptions({ name: 'PersonalNoiseRecord' })

// 从父组件注入设备可用性校验方法
type CheckEquipmentAvailabilityParams = {
  equipmentId: string
  startTime: string
  endTime: string
  sampleDate: string
  currentLogId?: number | null
  sampleNo?: string
}
const injectedCheckEquipmentAvailability = inject<
  (params: CheckEquipmentAvailabilityParams) => Promise<number | null>
>('checkEquipmentAvailability')

// 新增emitChange方法，放在顶部，确保模板可用
const emitChange = () => {
  emit('change', { ...form.value })
}

// 获取sampleObjectLocationed选项数组 - 始终返回完整的选项列表
const getSampleObjectLocationOptions = (rowIndex: number) => {
  const tableRow = form.value.table?.[rowIndex]
  let options: string[] = []
  if (tableRow && Array.isArray(tableRow.sampleObjectLocationed)) {
    options = tableRow.sampleObjectLocationed
  } else {
    options = originalOptionsMap.value.get(rowIndex) || []
  }

  if (!tableRow) return options
  const currentWorkplace = tableRow.workplace || ''
  const currentPost = tableRow.detectionPost || ''
  if (!currentWorkplace || !currentPost) return options
  const usedByOthers = new Set<string>()
  form.value.table.forEach((r: any, i: number) => {
    if (
      i !== rowIndex &&
      (r.workplace || '') === currentWorkplace &&
      (r.detectionPost || '') === currentPost
    ) {
      const sel = Array.isArray(r.sampleObjectLocation)
        ? r.sampleObjectLocation[0]
        : r.sampleObjectLocation
      if (sel) usedByOthers.add(sel)
    }
  })
  const currentSelected = Array.isArray(tableRow.sampleObjectLocation)
    ? tableRow.sampleObjectLocation[0]
    : tableRow.sampleObjectLocation
  return options.filter((opt) => !usedByOthers.has(opt) || opt === currentSelected)
}

// 默认按“工作场所+检测岗位”分组，为空选择的行自动分配不冲突的选项
const ensureUniqueDefaultSelection = () => {
  const usedMap = new Map<string, Set<string>>()
  form.value.table.forEach((row: any) => {
    const wp = row.workplace || ''
    const dp = row.detectionPost || ''
    if (!wp || !dp) return
    const key = `${wp}||${dp}`
    if (!usedMap.has(key)) usedMap.set(key, new Set<string>())
    const used = usedMap.get(key)!
    const currentSel = Array.isArray(row.sampleObjectLocation)
      ? row.sampleObjectLocation[0]
      : row.sampleObjectLocation
    if (currentSel) {
      used.add(currentSel)
      return
    }
    const opts: string[] = Array.isArray(row.sampleObjectLocationed)
      ? row.sampleObjectLocationed
      : []
    const pick = opts.find((o) => !used.has(o))
    if (pick) {
      row.sampleObjectLocation = [pick]
      used.add(pick)
    }
  })
}

// 单选读/写适配：内部存储数组，UI 单选
const getSingleSelect = (val: any) => (Array.isArray(val) ? val[0] ?? '' : val ?? '')
const setSingleSelect = (row: any, val: any) => {
  if (val !== '' && val != null) {
    const currentWorkplace = row.workplace || ''
    const currentPost = row.detectionPost || ''
    if (!currentWorkplace || !currentPost) {
      row.sampleObjectLocation = [val]
      emitChange()
      return
    }
    const conflict = form.value.table.some((r: any) => {
      if (r === row) return false
      const sel = Array.isArray(r.sampleObjectLocation)
        ? r.sampleObjectLocation[0]
        : r.sampleObjectLocation
      return (
        (r.workplace || '') === currentWorkplace &&
        (r.detectionPost || '') === currentPost &&
        sel === val
      )
    })
    if (conflict) {
      ElMessage && ElMessage.warning('同一工作场所+检测岗位下该选项已被占用，请选择其他项')
      return
    }
  }
  row.sampleObjectLocation = val === '' || val == null ? [] : [val]
  emitChange()
}

const defaultForm = () => ({
  taskNumber: '',
  sampleDate: '',
  company: '',
  address: '',
  collectorType: '',
  flowmeterInfo: [],
  samplingInstrumentInfo: '',
  basis: '',
  airPressure: '',
  type: '定期检测',
  item: '',
  humidity: '',
  calibrateSoundInfo: '',
  table: [
    {
      sampleNo: '',
      workplace: '',
      detectionPost: '',
      sampleObjectLocation: [],
      sampleObjectLocationed: [],
      samplingEquipmentNo: '',
      lowThreshold: '',
      standardSource: '',
      standardNoiseSource: '',
      calibrationBefore: '',
      calibrationAfter: '',
      dw: '',
      laeqTe: '',
      equipmentId: '',
      equipmentName: '',
      equipmentModel: '',
      workHours: '',
      workDays: '',
      flowRate: '',
      flowBefore: '',
      flowAfter: '',
      timeRange: ['', ''],
      sampleDuration: '',
      sampleVolume: '',
      dh: '8',
      productionStatus: '正常',
      earWearStatus: '佩戴',
      lex8h: '',
      lexw: '',
      protectionFacilityStatus: '',
      maskStatus: '',
      temperature: '',
      remark: '',
      logId: null
    }
  ]
})
const form = ref<any>(props.formData ? { ...defaultForm(), ...props.formData } : defaultForm())

const samplingInstrumentInfo = computed(() => {
  const mySet = new Set()
  form.value.table.forEach((row) => {
    console.log('row:', JSON.stringify( row))
    if (row.equipmentName && row.equipmentModel) {
      mySet.add(row.equipmentName +"/"+ row.equipmentModel+"/"+row.samplingEquipmentNo)
    }
  })
  return Array.from(mySet).join('，')
})

// 监听计算属性的变化并更新表单
watch(samplingInstrumentInfo, (newVal) => {
  form.value.samplingInstrumentInfo = newVal
  console.log('采样仪器信息更新:', JSON.stringify({
    samplingInstrumentInfo: newVal,
    table: form.value.table.map(row => ({
      equipmentName: row.equipmentName,
      equipmentModel: row.equipmentModel
    }))
  }))
  emitChange()
})


const calibrateSoundInfo = computed(() => {
  const mySet = new Set()
  form.value.table.forEach((row) => {
    if (row.equipmentName2 && row.equipmentModel2) {
      console.log('校准声源信息更新:', JSON.stringify({row }))
      mySet.add(row.equipmentName2 +"/"+ row.equipmentModel2+"/"+row.serialNumber2)
    }
  })
  return Array.from(mySet).join('，')
})

// 监听计算属性的变化并更新表单
watch(calibrateSoundInfo, (newVal) => {
  form.value.calibrateSoundInfo = newVal
  console.log('采样仪器信息更新:', JSON.stringify({
    samplingInstrumentInfo: newVal,
    table: form.value.table.map(row => ({
      equipmentName2: row.equipmentName2,
      equipmentModel2: row.equipmentModel2
    }))
  }))
  emitChange()
})

// 监听formData变化，自动赋值
watch(
  () => props.formData,
  (val) => {
    if (val) {
      const defaultData = defaultForm()
      Object.assign(form.value, defaultData, val)

      if (val.table && Array.isArray(val.table)) {
        form.value.table = val.table.map((tableRow, index) => {
          const newRow = { ...defaultData.table[0], ...tableRow }

          // 处理选项和选择的数据分离
          if (Array.isArray(tableRow.sampleObjectLocation)) {
            // 如果传入的数据中有 sampleObjectLocationed 字段，直接使用
            if (Array.isArray(tableRow.sampleObjectLocationed)) {
              newRow.sampleObjectLocationed = [...tableRow.sampleObjectLocationed]
              newRow.sampleObjectLocation = [...tableRow.sampleObjectLocation]
            } else {
              // 如果没有分离字段，判断是初始化还是用户数据
              const isInitialLoad = !originalOptionsMap.value.has(index)

              if (isInitialLoad) {
                // 初始化：sampleObjectLocation包含选项列表
                newRow.sampleObjectLocationed = [...tableRow.sampleObjectLocation]
                // 设置默认选择第一个
                newRow.sampleObjectLocation = tableRow.sampleObjectLocation.length > 0 ? [tableRow.sampleObjectLocation[0]] : []
              } else {
                // 用户数据：sampleObjectLocation包含用户选择
                newRow.sampleObjectLocation = [...tableRow.sampleObjectLocation]
                // 保持现有的选项不变
                const existingOptions = form.value.table?.[index]?.sampleObjectLocationed || originalOptionsMap.value.get(index) || []
                newRow.sampleObjectLocationed = [...existingOptions]
              }
            }
          } else {
            newRow.sampleObjectLocation = []
            newRow.sampleObjectLocationed = []
          }

          return newRow
        })
        // 为空选择的行按唯一规则分配默认选项
        ensureUniqueDefaultSelection()
      } else {
        form.value.table = defaultData.table
      }
    }
  },
  { immediate: true }
)

watch(
  () => props.type,
  (val) => {
    if (val) {
      if (props.type === 'fix') {
        label.value = '采样点及时机'
      } else {
        label.value = '采样对象'
      }
    }
  },
  { immediate: true }
)

watch(
  () => props.weatherRecords,
  (val) => {
    if (val) {
      form.value.airPressure = val.airPressure
      form.value.sampleDate = val.sampleDate
      form.value.temperature = val.temperature
      form.value.humidity = val.humidity
      console.log('个体噪声天气', JSON.stringify(props.weatherRecords))
    }
  },
  { immediate: true }
)

const addRow = () => {
  form.value.table.push({
    sampleNo: '',
    workplace: '',
    detectionPost: '',
    sampleObjectLocation: [],
    sampleObjectLocationed: [],
    samplingEquipmentNo: '',
    lowThreshold: '',
    standardSource: '',
    calibrationBefore: '',
    calibrationAfter: '',
    timeStart: '',
    timeEnd: '',
    sampleDuration: '',
    laeqTe: '',
    dh: '',
    lex8h: '',
    lexw: '',
    productionStatus: '',
    earWearStatus: '',
    remark: ''
  })
}

// 双击打开设备选择弹窗
const openFacilityDialog = (index: number, columnProp: string) => {
  if (columnProp === 'samplingEquipmentNo') {
    instrumentType.value='zsyq'
  }

  if (columnProp === 'standardNoiseSource') {
    instrumentType.value='bzsy'
  }
  currentRowIndex.value = index
  currentColumnProp.value = columnProp
  facilityDialogVisible.value = true
}
// 设备选择变化
const handleFacilitySelectionChange = (selection: any[]) => {
  const facility = Array.isArray(selection[0]) ? selection[0][0] : selection[0]
  selectedFacility.value = facility || null
}
// 确认选择设备
// equipmentId: string // 采样设备编号
// equipmentName: string // 采样设备编号
// equipmentModel: string // 采样设备编号
const handleFacilityConfirm = async () => {
  console.log('确认选择设备:', JSON.stringify(selectedFacility.value))
  if (currentRowIndex.value !== null && selectedFacility.value) {
    const row = form.value.table[currentRowIndex.value]
    const equipmentId = selectedFacility.value.id || ''
    const [startTime, endTime] = row.timeRange || ['', '']

    // 如果有时间范围，检查设备可用性（standardNoiseSource 不检查）
    if (startTime && endTime && injectedCheckEquipmentAvailability && currentColumnProp.value !== 'standardNoiseSource') {
      const newId = await injectedCheckEquipmentAvailability({
        equipmentId,
        startTime,
        endTime,
        sampleDate: form.value.sampleDate,
        currentLogId: row.logId,
        sampleNo: row.sampleNo || ''
      })
      if (newId) row.logId = newId
    }

    if (currentColumnProp.value === 'samplingEquipmentNo') {
      // 假设设备编号字段为 selectedFacility.value.no 或 name
      row.samplingEquipmentNo = selectedFacility.value.serialNumber || ''
      row.equipmentId = equipmentId
      row.equipmentName = selectedFacility.value.name || ''
      row.equipmentModel = selectedFacility.value.model || ''
      row.flowRate = selectedFacility.value.flowRate || ''
    }

    if (currentColumnProp.value === 'standardNoiseSource') {
      // 假设设备编号字段为 selectedFacility.value.no 或 name
      row.standardNoiseSource = selectedFacility.value.serialNumber || ''
      row.equipmentName2 = selectedFacility.value.name || ''
      row.equipmentModel2 = selectedFacility.value.model || ''
      row.serialNumber2 = selectedFacility.value.serialNumber || ''
    }
    console.log('选择设备form:', JSON.stringify(form.value))
    console.log('选择设备:', JSON.stringify(selectedFacility.value))
    facilityDialogVisible.value = false
    selectedFacility.value = null
    currentRowIndex.value = null
    ElMessage.success('选择设备成功')
    emitChange()
  } else {
    ElMessage.warning('请选择设备')
  }
}

// 校验本表单必填项不为空；供父组件调用
const validateRequired = (): boolean => {
  // 头部表单必填项
  const headerEmpty: string[] = []
  if (!form.value.sampleDate) headerEmpty.push('采样日期')
  if (form.value.airPressure === '') headerEmpty.push('气压')
  if (!form.value.type) headerEmpty.push('检测类别')
  if (!form.value.samplingInstrumentInfo) headerEmpty.push('测量仪器信息')
  if (!form.value.calibrateSoundInfo) headerEmpty.push('标准声源')
  if (headerEmpty.length > 0) {
    ElMessage && ElMessage.warning("【"+props.labelName+"】"+"【"+form.value.item+"】"+`—未填写：${headerEmpty.join('、')}`)
    return false
  }

  // 表格必填项
  const fieldLabels: Record<string, string> = {
    sampleNo: '测量编号',
    workplace: '工作场所',
    detectionPost: '检测岗位',
    sampleObjectLocation: '测量对象/佩戴人员',
    samplingEquipmentNo: '仪器编号',
    standardNoiseSource: '标准声源',
    calibrationBefore: '测量前读数值',
    calibrationAfter: '测量后读数值',
    timeRange: '测量起止时间',
    sampleDuration: '测量时长',
    laeqTe: 'LAeq,Te[dB(A)]',
    dh: '代表时间h/d',
    workDays: '代表时间d/w',
    productionStatus: '设备运行情况',
    earWearStatus: '个体防护情况'
  }

  for (let i = 0; i < form.value.table.length; i++) {
    const row = form.value.table[i]
    const emptyFields: string[] = []

    if (!row.sampleNo) emptyFields.push(fieldLabels.sampleNo)
    if (!row.workplace) emptyFields.push(fieldLabels.workplace)
    if (!row.detectionPost) emptyFields.push(fieldLabels.detectionPost)
    const singleLocation = Array.isArray(row.sampleObjectLocation)
      ? (row.sampleObjectLocation[0] || '')
      : (row.sampleObjectLocation || '')
    if (!singleLocation) emptyFields.push(fieldLabels.sampleObjectLocation)
    if (!row.samplingEquipmentNo) emptyFields.push(fieldLabels.samplingEquipmentNo)
    if (!row.standardNoiseSource) emptyFields.push(fieldLabels.standardNoiseSource)
    if (row.calibrationBefore === '') emptyFields.push(fieldLabels.calibrationBefore)
    if (row.calibrationAfter === '') emptyFields.push(fieldLabels.calibrationAfter)

    const [start, end] = Array.isArray(row.timeRange) ? row.timeRange : ['', '']
    if (!start || !end) emptyFields.push(fieldLabels.timeRange)
    if (row.sampleDuration === '') emptyFields.push(fieldLabels.sampleDuration)
    if (row.laeqTe === '') emptyFields.push(fieldLabels.laeqTe)
    if (row.dh === '') emptyFields.push(fieldLabels.dh)
    if (row.workDays === '') emptyFields.push(fieldLabels.workDays)
    if (row.productionStatus === '') emptyFields.push(fieldLabels.productionStatus)
    if (row.earWearStatus === '') emptyFields.push(fieldLabels.earWearStatus)

    if (emptyFields.length > 0) {
      ElMessage && ElMessage.warning("【"+props.labelName+"】"+"【"+form.value.item+"】"+"【"+row.sampleNo+"】"+`—未填写：${emptyFields.join('、')}`)
      return false
    }
  }

  return true
}

// 暴露数据给父组件
defineExpose({
  form,
  addRow,
  openFacilityDialog,
  handleFacilitySelectionChange,
  handleFacilityConfirm,
  validateRequired
})

onMounted(() => {})
</script>

<style lang="scss" scoped>
.chem-title {
  font-size: 26px;
  font-weight: 600;
  color: #222;
  flex-grow: 1;
  text-align: center;
}

.chem-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 0 0 24px 0;
  padding: 16px 0 16px 0;
  border-bottom: 1.5px solid #409EFF;
  font-size: 20px;
  font-weight: 600;
  color: #409EFF;
  background: none;
  border-radius: 0;
  box-shadow: none;
  letter-spacing: 1px;
}

.chem-form {
  background: none;
  box-shadow: none;
  border-radius: 0;
  margin-bottom: 0;


  :deep(.el-input__inner) {
    border-radius: 0 !important;
    box-shadow: none !important;

  }

  :deep(.el-form-item__label) {
    white-space: nowrap;
  }
}

.chem-btns {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  align-items: center;
  margin-top: 0;
}

.chem-table {
  margin-top: 18px;
  --el-table-border-radius: 0 !important;
  --el-table-header-bg-color: #f7f8fa;
  --el-table-border-color: #e5e6eb;
  box-shadow: none !important;
  border-radius: 0 !important;

  :deep(.el-table__header th) {
    background: #f7f8fa !important;
    font-weight: 600;
    font-size: 14px;
    border-radius: 0 !important;
    padding: 8px 0 !important;

    .cell {
      padding-left: 0px !important;
      padding-right: 0px !important;
    }
  }

  // 设置表格行高
  :deep(.el-table__body td) {
    border-radius: 0 !important;

    font-size: 14px;
    padding: 0 !important;
    // 列和单元格的边距
    .cell {
      padding: 0px 0px;
    }
  }

  // 去掉输入框边框
  :deep(.el-input__wrapper) {
    border-radius: 0 !important;
    box-shadow: none !important;

  }

  // 针对下拉选择框的所有相关元素去掉边框
  :deep(.el-select__wrapper) {
    border: none !important;
    box-shadow: none !important;
  }
}

.input-with-unit {
  position: relative;
}

.unit-text {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  color: #909399;
  font-size: 14px;
  pointer-events: none;
  z-index: 1;
}
</style>
